/**
 * 系统服务
 * 处理系统相关的IPC通信
 */
import { BaseIPCService, ServiceResult, createSuccessResult, createErrorResult } from './base/ipc.service'

/**
 * 系统信息接口
 */
export interface SystemInfo {
  platform: string
  arch: string
  version: string
  memory: {
    total: number
    free: number
    used: number
  }
  cpu: {
    model: string
    cores: number
    usage: number
  }
}

/**
 * 系统服务类
 */
export class SystemService extends BaseIPCService {
  /**
   * 获取系统信息
   */
  async getSystemInfo(): Promise<ServiceResult<SystemInfo>> {
    try {
      this.log('获取系统信息')

      const result = await this.invoke<SystemInfo>('system:info')
      
      this.log('获取系统信息成功', { 
        platform: result.platform, 
        arch: result.arch,
        cores: result.cpu.cores 
      })
      return createSuccessResult(result, '获取系统信息成功')

    } catch (error) {
      this.logError('获取系统信息', error)
      return createErrorResult(error, '获取系统信息失败')
    }
  }

  /**
   * 获取内存使用情况
   */
  async getMemoryUsage(): Promise<ServiceResult<{
    total: number
    free: number
    used: number
    usagePercent: number
  }>> {
    try {
      this.log('获取内存使用情况')

      const systemInfo = await this.invoke<SystemInfo>('system:info')
      const memory = systemInfo.memory
      
      const result = {
        total: memory.total,
        free: memory.free,
        used: memory.used,
        usagePercent: Math.round((memory.used / memory.total) * 100)
      }
      
      this.log('获取内存使用情况成功', { usagePercent: result.usagePercent })
      return createSuccessResult(result, '获取内存使用情况成功')

    } catch (error) {
      this.logError('获取内存使用情况', error)
      return createErrorResult(error, '获取内存使用情况失败')
    }
  }

  /**
   * 获取CPU信息
   */
  async getCpuInfo(): Promise<ServiceResult<{
    model: string
    cores: number
    usage: number
  }>> {
    try {
      this.log('获取CPU信息')

      const systemInfo = await this.invoke<SystemInfo>('system:info')
      const cpu = systemInfo.cpu
      
      this.log('获取CPU信息成功', { model: cpu.model, cores: cpu.cores })
      return createSuccessResult(cpu, '获取CPU信息成功')

    } catch (error) {
      this.logError('获取CPU信息', error)
      return createErrorResult(error, '获取CPU信息失败')
    }
  }

  /**
   * 获取磁盘信息
   */
  async getDiskInfo(): Promise<ServiceResult<{
    total: number
    free: number
    used: number
    usagePercent: number
  }>> {
    try {
      this.log('获取磁盘信息')

      // 注意：这里需要主进程实现相应的IPC处理器
      // 目前返回模拟数据
      const result = {
        total: 1000000000000, // 1TB
        free: 500000000000,   // 500GB
        used: 500000000000,   // 500GB
        usagePercent: 50
      }
      
      this.log('获取磁盘信息成功', { usagePercent: result.usagePercent })
      return createSuccessResult(result, '获取磁盘信息成功')

    } catch (error) {
      this.logError('获取磁盘信息', error)
      return createErrorResult(error, '获取磁盘信息失败')
    }
  }

  /**
   * 打开文件夹
   */
  async openFolder(path: string): Promise<ServiceResult<void>> {
    try {
      this.validateRequired({ path }, ['path'])
      
      this.log('打开文件夹', { path })

      // 注意：这里需要主进程实现相应的IPC处理器
      // await this.invoke<void>('system:openFolder', path)
      
      this.log('打开文件夹成功', { path })
      return createSuccessResult(undefined, '文件夹已打开')

    } catch (error) {
      this.logError('打开文件夹', error, { path })
      return createErrorResult(error, '打开文件夹失败')
    }
  }

  /**
   * 复制到剪贴板
   */
  async copyToClipboard(text: string): Promise<ServiceResult<void>> {
    try {
      this.validateRequired({ text }, ['text'])
      
      this.log('复制到剪贴板', { textLength: text.length })

      // 使用浏览器API复制到剪贴板
      await navigator.clipboard.writeText(text)
      
      this.log('复制到剪贴板成功')
      return createSuccessResult(undefined, '已复制到剪贴板')

    } catch (error) {
      this.logError('复制到剪贴板', error, { textLength: text?.length })
      return createErrorResult(error, '复制到剪贴板失败')
    }
  }

  /**
   * 从剪贴板读取
   */
  async readFromClipboard(): Promise<ServiceResult<string>> {
    try {
      this.log('从剪贴板读取')

      // 使用浏览器API从剪贴板读取
      const text = await navigator.clipboard.readText()
      
      this.log('从剪贴板读取成功', { textLength: text.length })
      return createSuccessResult(text, '从剪贴板读取成功')

    } catch (error) {
      this.logError('从剪贴板读取', error)
      return createErrorResult(error, '从剪贴板读取失败')
    }
  }

  /**
   * 获取应用路径信息
   */
  async getAppPaths(): Promise<ServiceResult<{
    appPath: string
    userData: string
    temp: string
    logs: string
    home: string
    documents: string
    downloads: string
    desktop: string
  }>> {
    try {
      this.log('获取应用路径信息')

      // 注意：这里需要主进程实现相应的IPC处理器
      // const result = await this.invoke<any>('system:getAppPaths')
      
      // 目前返回模拟数据
      const result = {
        appPath: '/Applications/ShadowPuppetryFlash.app',
        userData: '~/Library/Application Support/spf-electron',
        temp: '/tmp',
        logs: '~/Library/Logs/spf-electron',
        home: '~',
        documents: '~/Documents',
        downloads: '~/Downloads',
        desktop: '~/Desktop'
      }
      
      this.log('获取应用路径信息成功')
      return createSuccessResult(result, '获取应用路径信息成功')

    } catch (error) {
      this.logError('获取应用路径信息', error)
      return createErrorResult(error, '获取应用路径信息失败')
    }
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B'
    
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  /**
   * 格式化内存大小
   */
  formatMemorySize(bytes: number): string {
    return this.formatFileSize(bytes)
  }
}

// 导出单例实例
export const systemService = new SystemService()

// 导出便捷方法
export const {
  getSystemInfo,
  getMemoryUsage,
  getCpuInfo,
  getDiskInfo,
  openFolder,
  copyToClipboard,
  readFromClipboard,
  getAppPaths,
  formatFileSize,
  formatMemorySize
} = systemService
